/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
 * MemFabric_Hybrid is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
*/
#include <cstdint>

#include "hybm_mem_slice.h"

namespace ock {
namespace mf {
union SliceIdUnion {
    struct SliceDetail {
        uint64_t magic_ : 40;         /* to verify hybm_mem_slice_t ptr */
        uint64_t index_ : 16;         /* id of mem slice  */
        uint64_t memType_ : 4;        /* device or host memory */
        uint64_t memPageTblType_ : 2; /* use CANN SVM page table or HyBM page table */
        uint64_t reserved : 2;
    } detail;
    uint64_t number;
    void *address;
};

hybm_mem_slice_t MemSlice::ConvertToId() const noexcept
{
    SliceIdUnion idUnion{};
    idUnion.detail.magic_ = magic_;
    idUnion.detail.index_ = index_;
    idUnion.detail.memType_ = memType_;
    idUnion.detail.memPageTblType_ = memPageTblType_;
    idUnion.detail.reserved = 0;
    return idUnion.address;
}

bool MemSlice::ValidateId(hybm_mem_slice_t slice) const
{
    SliceIdUnion idUnion{};
    idUnion.address = slice;
    return idUnion.address == ConvertToId();
}

uint64_t MemSlice::GetIndexFrom(hybm_mem_slice_t slice) noexcept
{
    SliceIdUnion idUnion{};
    idUnion.address = slice;
    return idUnion.detail.index_;
}
}
}